﻿using System;
using System.Linq;
using _5E.Utils.CollectionHelper.GenericExtension;

namespace _5E.Utils.DbHelper.EasySQL.Creator
{
    /// <summary>
    /// 程序说明：创建更新SQL
    /// 创建作者：ahl5esoft
    /// 创建时间：2012-04-16
    /// </summary>
    class UpdateCreator : BaseCreator, ICustomColumn, ICustomWhere
    {
        #region 变量

        private const string UPDATE_SQL_FORMAT = "UPDATE {0} SET {1} {2}";

        private string[] m_Columns = null;

        private string m_Where = null;

        #endregion

        #region 实例方法

        public ICustomColumn SetColumns(string[] propertyNames)
        {
            m_Columns = propertyNames;
            return this;
        }

        public ICustomWhere SetWhere(string where)
        {
            m_Where = ParseCondition.ToWhere(where, AllColumns);
            return this;
        }

        public override string CreateSQL()
        {
            var columnString = GetColumnString();
            var sql = string.Format(UPDATE_SQL_FORMAT, TableName, columnString, m_Where);
            return sql;
        }

        private string GetColumnString()
        {
            var filterColumns = m_Columns.Exchange(AllColumns.Keys.ToArray());
            var columns = Array.ConvertAll(filterColumns, propertyName =>
            {
                string columnName = GetColumnName(propertyName);
                var condition = ToEqualString(columnName, propertyName);
                return condition;
            });
            var columnString = ToColumnString(columns);
            return columnString;
        }

        protected override void Reset()
        {
            m_Where = null;
            m_Columns = null;
        }

        #endregion
    }
}
